package cn.edu.zjut.security;

import cn.edu.zjut.base.BaseController;
import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @description:
 * @author:ZhouDan
 * @date: 2020/8/10
 * @version: 1.0
 */
@Component
@RestController
public class MyLogoutSuccessHandler extends BaseController implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        HttpSession session = httpServletRequest.getSession();
        // 让以前的session失效
        session.invalidate();
        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        Map<String, Object> userMap = response(200,null);
        PrintWriter out = httpServletResponse.getWriter();
        JSONObject json = new JSONObject();
        for (Map.Entry<String, Object> map1 : userMap.entrySet()) {
            json.put(map1.getKey(), map1.getValue());
        }
        out.write(json.toString());
    }
}
